package com.bjc.platform.util;

import java.io.IOException;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.*;

/**
 * JSON和JAVA的POJO的相互转换, 字符串和JSON的转换 JSONHelper.java
 */
public final class JSONHelper {
	private static final Logger logger = LoggerFactory
			.getLogger(JSONHelper.class);

	public static JsonGenerator jsonGenerator = null;
	private static ObjectMapper mapper = new ObjectMapper();
	static {
		//@ TODO  fasterxml.jackson 的config配置
//		mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//		mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
	}

	/**
	 * 将JSON转换成数组,其中valueClz为数组中存放的对象的Class 
	 * Example: String[] arr =  (String[])json2Array("[{...},{...}]",String[].class);
	 * 
	 * @param json
	 * @param valueClz
	 * @return
	 * @throws Exception
	 */
	public static Object json2Array(String json, Class valueClz)
			throws Exception {
		return mapper.readValue(json, valueClz);
	}

	/**
	 * 将 Map转换为JSON字符串
	 * 
	 * @param object
	 * @return
	 */
	public static String map2json(Object object) throws Exception {
		return mapper.writeValueAsString(object);
	}

	/**
	 * 将JSON转换成Map
	 * 
	 * @param json
	 * @return
	 */
	public static Map json2Map(String json) throws Exception {
		return mapper.readValue(json, Map.class);
	}

	/**
	 * 将JSON转换成POJO,其中beanClz为POJO的Class
	 * 
	 * @param json
	 * @param beanClz
	 * @return
	 */
	public static Object json2Object(String json, Class beanClz)
			throws Exception {
		return mapper.readValue(json, beanClz);
	}

	/**
	 * json转换为java对象
	 * 
	 * 
	 * @param <T>
	 *            要转换的对象
	 * @param json
	 *            字符串
	 * @param valueType
	 *            对象的class
	 * @return 返回对象
	 */
	public static <T> T fromJsonToObject(String json, Class<T> valueType) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.readValue(json, valueType);
		} catch (JsonParseException e) {
			logger.error("JsonParseException: ", e);
		} catch (JsonMappingException e) {
			logger.error("JsonMappingException: ", e);
		} catch (IOException e) {
			logger.error("IOException: ", e);
		}
		return null;
	}

}
